/**
 * Copyright (C) 2012 Chris Xinyue Zhao <hasszhao@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.lightlib.sample.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.code.lightlib.sample.R;

import de.cellular.lib.lightlib.backend.LLImageResponse;
import de.cellular.lib.lightlib.backend.LLRequest;
import de.cellular.lib.lightlib.backend.LLRequestImage;
import de.cellular.lib.lightlib.backend.LLRequestImage.RequestedSize;
import de.cellular.lib.lightlib.backend.base.ILLRequestResponsible;
import de.cellular.lib.lightlib.backend.base.LLAbstractResponse;
import de.cellular.lib.lightlib.backend.base.LLRequestResponsibleSimpleObject;
import de.cellular.lib.lightlib.log.LL;
import de.cellular.lib.lightlib.ui.fragment.LLRequestingFragment;

/**
 * The Class ExampleBackend that shows test of backend APIs.
 * @author Chris.Z <hasszhao@gmail.com>
 */
public class ExampleBackend extends LLRequestingFragment implements OnClickListener
{
    private TextView       mText;
    private ImageView      mImage;
    private LLRequest      mRequest;
    private DisplayMetrics metrics;

    @Override
    public View onCreateView( LayoutInflater _inflater, ViewGroup _container, Bundle _savedInstanceState ) {
        View v = View.inflate( getActivity().getApplicationContext(), R.layout.ll_backend, null );
        mText = (TextView) v.findViewById( R.id.tv_data );
        mImage = (ImageView) v.findViewById( R.id.iv_data );

        v.findViewById( R.id.btn_push_data ).setOnClickListener( this );
        v.findViewById( R.id.btn_load_image ).setOnClickListener( this );

        metrics = new DisplayMetrics();
        ((WindowManager) getActivity().getSystemService( Context.WINDOW_SERVICE )).getDefaultDisplay().getMetrics(
                metrics );
        return v;
    }

    @Override
    public void onPause() {
        super.onPause();
        cancel();
    }

    /**
     * Cancel a current running request.
     */
    private void cancel() {
        if( mRequest != null ) {
            mRequest.abort();
        }
        getActivity().setProgressBarIndeterminateVisibility( false ); 
    }
    
    @Override
    public void onDetach() { 
        super.onDetach();
        getActivity().setProgressBarIndeterminateVisibility( false ); 
    }

    /**
     * Push a request
     * 
     * 
     * @param _v
     *            the _v
     */
    public void push( View _v ) {
        cancel();
        getActivity().setProgressBarIndeterminateVisibility( true ); 
        mRequest = LLRequest.start(
                getActivity().getApplicationContext(),
                new LLRequestResponsibleSimpleObject( (ILLRequestResponsible) this ),
                LLRequest.Method.GET,
                "http://m.otto.de/?getAndroidFeed=1&view=AppWebShop_Android&udid=45645645645645",
                null );
    }

    /**
     * Load bitmaps
     * 
     * @param _v
     *            the _v
     */
    public void load( View _v ) {
        cancel();
        RequestedSize size = new RequestedSize();
        size.reqWidth = metrics.widthPixels;
        size.reqHeight = metrics.heightPixels;

        getActivity().setProgressBarIndeterminateVisibility( true ); 
        mRequest = LLRequestImage.start(
                getActivity().getApplicationContext(),
                new LLRequestResponsibleSimpleObject( (ILLRequestResponsible) this ),
                LLRequest.Method.GET,
                "http://imgk.zol.com.cn/ideapad/3056/a3055436_s.jpg",
                size,
                null );
    }

    @Override
    public void onRequestImageSuccessed( Message _msg ) {
        if( _msg.obj instanceof LLImageResponse ) {
            LLImageResponse response = (LLImageResponse) _msg.obj;
            mImage.setImageBitmap( response.getBitmap() );
        }
        else {
            LL.e( "_msg.obj should be an instance of LLImageResponse." );
        }
        getActivity().setProgressBarIndeterminateVisibility( false ); 
    }

    @Override
    public void onRequestSuccessed( Message _msg ) {
        if( _msg.obj instanceof LLAbstractResponse ) {
            LLAbstractResponse response = (LLAbstractResponse) _msg.obj;
            mText.setText( response.toString() );
        }
        else {
            LL.e( "_msg.obj should be an instance of LLResponse." );
        }
        getActivity().setProgressBarIndeterminateVisibility( false ); 
    }

    @Override
    public void onRequestAborted( Message _msg ) {

    }

    @Override
    public void onRequestFailed( Message _msg ) {
    }

    @Override
    public void onRequestFinished( Message _msg ) {

    }

    @Override
    public void onRequestImageFailed( Message _msg ) {

    }

    @Override
    public void onClick( View _v ) {
        switch( _v.getId() )
        {
            case R.id.btn_push_data:
                push( _v );
            break;

            case R.id.btn_load_image:
                load( _v );
            break;
            default:
            break;
        }
    }
}
